"""
API路由模块
处理所有API相关的路由
"""
import os
import re
from pathlib import Path
from flask import request, jsonify, send_file
from datetime import datetime


def register_api_routes(app, config_manager, proxy_process_manager, system_proxy_manager, log_manager):
    """注册API路由"""
    
    @app.route('/api/config', methods=['GET'])
    def get_config():
        """获取配置"""
        config = config_manager.load_config()
        return jsonify(config)

    @app.route('/api/config', methods=['POST'])
    def save_config():
        """保存配置"""
        config = request.json
        config_manager.save_config(config)
        return jsonify({'success': True})

    @app.route('/api/rules', methods=['POST'])
    def add_rule():
        """添加规则"""
        rule = request.json
        config_manager.add_rule(rule)
        
        # 如果代理服务器正在运行，重启以应用新配置
        if proxy_process_manager.is_proxy_running():
            restart_success, restart_message = proxy_process_manager.restart_proxy_process()
            return jsonify({
                'success': True, 
                'restarted': restart_success,
                'restart_message': restart_message
            })
        
        return jsonify({'success': True, 'restarted': False})

    @app.route('/api/rules/<int:index>', methods=['PUT'])
    def update_rule(index):
        """更新规则"""
        rule = request.json
        config_manager.update_rule(index, rule)
        
        # 如果代理服务器正在运行，重启以应用新配置
        if proxy_process_manager.is_proxy_running():
            restart_success, restart_message = proxy_process_manager.restart_proxy_process()
            return jsonify({
                'success': True, 
                'restarted': restart_success,
                'restart_message': restart_message
            })
        
        return jsonify({'success': True, 'restarted': False})

    @app.route('/api/rules/<int:index>', methods=['DELETE'])
    def delete_rule(index):
        """删除规则"""
        config_manager.delete_rule(index)
        
        # 如果代理服务器正在运行，重启以应用新配置
        if proxy_process_manager.is_proxy_running():
            restart_success, restart_message = proxy_process_manager.restart_proxy_process()
            return jsonify({
                'success': True, 
                'restarted': restart_success,
                'restart_message': restart_message
            })
        
        return jsonify({'success': True, 'restarted': False})

    @app.route('/api/rules/<int:index>/toggle', methods=['POST'])
    def toggle_rule(index):
        """切换规则的启用/禁用状态"""
        new_status = config_manager.toggle_rule(index)
        if new_status is None:
            return jsonify({'success': False, 'error': '规则不存在'}), 404
        
        # 如果代理服务器正在运行，重启以应用新配置
        if proxy_process_manager.is_proxy_running():
            restart_success, restart_message = proxy_process_manager.restart_proxy_process()
            return jsonify({
                'success': True,
                'enabled': new_status,
                'restarted': restart_success,
                'restart_message': restart_message
            })
        
        return jsonify({'success': True, 'enabled': new_status, 'restarted': False})

    @app.route('/api/rules/<int:index>/enable', methods=['POST'])
    def enable_rule(index):
        """启用规则"""
        data = request.json or {}
        enabled = data.get('enabled', True)
        
        success = config_manager.set_rule_enabled(index, enabled)
        if not success:
            return jsonify({'success': False, 'error': '规则不存在'}), 404
        
        # 如果代理服务器正在运行，重启以应用新配置
        if proxy_process_manager.is_proxy_running():
            restart_success, restart_message = proxy_process_manager.restart_proxy_process()
            return jsonify({
                'success': True,
                'enabled': enabled,
                'restarted': restart_success,
                'restart_message': restart_message
            })
        
        return jsonify({'success': True, 'enabled': enabled, 'restarted': False})

    @app.route('/api/regex/validate', methods=['POST'])
    def validate_regex():
        """验证正则表达式语法"""
        data = request.json or {}
        pattern = data.get('pattern', '')
        
        if not pattern:
            return jsonify({
                'success': False,
                'valid': False,
                'error': '正则表达式不能为空'
            })
        
        try:
            re.compile(pattern)
            return jsonify({
                'success': True,
                'valid': True,
                'message': '正则表达式语法正确'
            })
        except re.error as e:
            return jsonify({
                'success': True,
                'valid': False,
                'error': f'正则表达式语法错误: {str(e)}'
            })

    @app.route('/api/regex/test', methods=['POST'])
    def test_regex_match():
        """测试正则表达式匹配"""
        data = request.json or {}
        pattern = data.get('pattern', '')
        test_url = data.get('test_url', '')
        pattern_type = data.get('pattern_type', 'string')
        
        if not pattern:
            return jsonify({
                'success': False,
                'error': '匹配模式不能为空'
            })
        
        if not test_url:
            return jsonify({
                'success': False,
                'error': '测试URL不能为空'
            })
        
        try:
            if pattern_type == 'regex':
                # 正则表达式匹配
                compiled_regex = re.compile(pattern)
                match_result = compiled_regex.search(test_url)
                matched = bool(match_result)
                
                match_info = {}
                if match_result:
                    match_info = {
                        'full_match': match_result.group(0),
                        'start_pos': match_result.start(),
                        'end_pos': match_result.end(),
                        'groups': match_result.groups() if match_result.groups() else []
                    }
                
                return jsonify({
                    'success': True,
                    'matched': matched,
                    'pattern_type': 'regex',
                    'match_info': match_info
                })
            else:
                # 字符串包含匹配
                matched = pattern in test_url
                return jsonify({
                    'success': True,
                    'matched': matched,
                    'pattern_type': 'string'
                })
                
        except re.error as e:
            return jsonify({
                'success': False,
                'error': f'正则表达式错误: {str(e)}'
            })
        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'匹配测试失败: {str(e)}'
            })

    @app.route('/api/rules/test', methods=['POST'])
    def test_rule_match():
        """测试规则匹配"""
        data = request.json or {}
        test_url = data.get('test_url', '')
        
        if not test_url:
            return jsonify({
                'success': False,
                'error': '测试URL不能为空'
            })
        
        try:
            config = config_manager.load_config()
            rules = config.get('rules', [])
            
            matched_rules = []
            
            for i, rule in enumerate(rules):
                # 检查规则是否启用
                if not rule.get('enabled', True):
                    continue
                
                pattern = rule.get('pattern', '')
                pattern_type = rule.get('pattern_type', 'string')
                
                matched = False
                match_info = {}
                
                if pattern_type == 'regex':
                    try:
                        compiled_regex = re.compile(pattern)
                        match_result = compiled_regex.search(test_url)
                        matched = bool(match_result)
                        
                        if match_result:
                            match_info = {
                                'full_match': match_result.group(0),
                                'start_pos': match_result.start(),
                                'end_pos': match_result.end(),
                                'groups': match_result.groups() if match_result.groups() else []
                            }
                    except re.error:
                        # 正则表达式错误，跳过此规则
                        continue
                else:
                    matched = pattern in test_url
                
                if matched:
                    rule_info = {
                        'index': i,
                        'pattern': pattern,
                        'pattern_type': pattern_type,
                        'matched': True,
                        'match_info': match_info,
                        'rule_type': 'mock' if rule.get('type') == 'mock' or 'mock_response' in rule else 'proxy'
                    }
                    matched_rules.append(rule_info)
            
            return jsonify({
                'success': True,
                'test_url': test_url,
                'matched_rules': matched_rules,
                'first_match': matched_rules[0] if matched_rules else None
            })
            
        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'规则测试失败: {str(e)}'
            })

    @app.route('/api/proxy/status', methods=['GET'])
    def get_proxy_status():
        """获取代理状态"""
        proxy_status = proxy_process_manager.get_proxy_status()
        return jsonify({
            'server_running': proxy_status['running'],
            'server_details': proxy_status,
            'system_proxy': system_proxy_manager.get_proxy_status()
        })

    @app.route('/api/proxy/start', methods=['POST'])
    def start_proxy_server():
        """启动代理服务器"""
        data = request.json or {}
        # 如果没有指定host和port，将从配置文件读取
        host = data.get('host')  # 不提供默认值，让进程管理器从配置读取
        port = data.get('port')  # 不提供默认值，让进程管理器从配置读取
        log_level = data.get('log_level')  # 可选的日志级别参数
        
        success, message = proxy_process_manager.start_proxy_process(host, port, log_level)
        return jsonify({
            'success': success,
            'message': message,
            'running': proxy_process_manager.is_proxy_running()
        })

    @app.route('/api/proxy/stop', methods=['POST'])
    def stop_proxy_server():
        """停止代理服务器"""
        success, message = proxy_process_manager.stop_proxy_process()
        return jsonify({
            'success': success,
            'message': message,
            'running': proxy_process_manager.is_proxy_running()
        })

    @app.route('/api/system-proxy/enable', methods=['POST'])
    def enable_system_proxy():
        """启用系统代理"""
        data = request.json or {}
        # 如果没有指定host和port，将从配置文件读取
        host = data.get('host')  # 不提供默认值，让系统代理管理器从配置读取
        port = data.get('port')  # 不提供默认值，让系统代理管理器从配置读取
        success = system_proxy_manager.enable_proxy(host, port)
        return jsonify({'success': success})

    @app.route('/api/system-proxy/disable', methods=['POST'])
    def disable_system_proxy():
        """禁用系统代理"""
        success = system_proxy_manager.disable_proxy()
        return jsonify({'success': success})

    @app.route('/api/network-services', methods=['GET'])
    def get_network_services():
        """获取网络服务列表"""
        services = system_proxy_manager.get_network_services()
        return jsonify({'services': services})

    @app.route('/api/server-config', methods=['GET'])
    def get_server_config():
        """获取服务器配置"""
        server_config = config_manager.get_server_config()
        return jsonify({
            'success': True,
            'config': server_config
        })

    @app.route('/api/server-config', methods=['POST'])
    def update_server_config():
        """更新服务器配置"""
        try:
            server_config = request.json
            config_manager.update_server_config(server_config)
            return jsonify({
                'success': True,
                'message': '服务器配置已更新'
            })
        except ValueError as e:
            return jsonify({
                'success': False,
                'error': str(e)
            }), 400
        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'更新配置失败: {str(e)}'
            }), 500

    @app.route('/api/logs', methods=['GET'])
    def get_logs():
        """获取日志列表"""
        rule_filter = request.args.get('rule', '')
        level_filter = request.args.get('level', '')
        date_filter = request.args.get('date', '')
        limit = int(request.args.get('limit', 500))
        
        logs = log_manager.read_logs(
            rule_filter=rule_filter if rule_filter else None,
            level_filter=level_filter if level_filter else None,
            date_filter=date_filter if date_filter else None,
            limit=limit
        )
        
        return jsonify({
            'logs': logs,
            'total': len(logs),
            'filters': {
                'rule': rule_filter,
                'level': level_filter,
                'date': date_filter
            }
        })

    @app.route('/api/cert/status', methods=['GET'])
    def get_cert_status():
        """获取证书状态"""
        try:
            cert_path = Path.home() / '.mitmproxy' / 'mitmproxy-ca-cert.pem'
            
            if cert_path.exists():
                # 获取证书创建时间
                stat = cert_path.stat()
                created_time = datetime.fromtimestamp(stat.st_ctime).strftime('%Y-%m-%d %H:%M:%S')
                
                return jsonify({
                    'exists': True,
                    'path': str(cert_path),
                    'created_time': created_time,
                    'size': stat.st_size
                })
            else:
                return jsonify({'exists': False})
        except Exception as e:
            return jsonify({'exists': False, 'error': str(e)})

    @app.route('/api/cert/download', methods=['GET'])
    def download_cert():
        """下载证书文件"""
        try:
            cert_path = Path.home() / '.mitmproxy' / 'mitmproxy-ca-cert.pem'
            
            if cert_path.exists():
                return send_file(
                    str(cert_path),
                    as_attachment=True,
                    download_name='mitmproxy-ca-cert.pem',
                    mimetype='application/x-pem-file'
                )
            else:
                return jsonify({'error': '证书文件不存在'}), 404
        except Exception as e:
            return jsonify({'error': str(e)}), 500

    @app.route('/api/execute-curl', methods=['POST'])
    def execute_curl():
        """执行curl命令并返回响应数据"""
        try:
            # 导入curl模块
            from ..curl import CurlExecutor, CurlResponseParser
            
            data = request.json or {}
            curl_command = data.get('curl_command', '').strip()
            
            if not curl_command:
                return jsonify({
                    'success': False,
                    'error': '请提供curl命令'
                }), 400
            
            # 创建执行器和解析器
            executor = CurlExecutor()
            parser = CurlResponseParser()
            
            # 执行curl命令
            execution_result = executor.execute_curl(curl_command)
            
            if execution_result['success']:
                # 解析响应数据为Mock格式
                response_data = execution_result['response_data']
                mock_data = parser.parse_response_for_mock(response_data)
                
                return jsonify({
                    'success': True,
                    'response_data': mock_data,
                    'execution_time': execution_result['execution_time'],
                    'warnings': execution_result.get('warnings', [])
                })
            else:
                return jsonify({
                    'success': False,
                    'error': execution_result['error'],
                    'execution_time': execution_result['execution_time'],
                    'warnings': execution_result.get('warnings', [])
                }), 400
                
        except ImportError as e:
            return jsonify({
                'success': False,
                'error': f'curl模块导入失败: {str(e)}'
            }), 500
        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'执行curl命令时发生错误: {str(e)}'
            }), 500